package com.olympia.myapp.activity;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.xml.sax.InputSource;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.olympia.myapp.R;
import com.olympia.myapp.base.BaseActivity;
import com.olympia.myapp.custom.Dialog_Confirm;
import com.olympia.myapp.custom.Dialog_Confirm.ProcessDialogConfirm;
import com.olympia.myapp.entity.Player;
import com.olympia.myapp.entity.QuestionVD;
import com.olympia.myapp.server.HttpConnection;
import com.olympia.myapp.util.AnimationControl;
import com.olympia.myapp.util.Constants;
import com.olympia.myapp.util.ControlListener;
import com.olympia.myapp.util.Reminder;
import com.olympia.myapp.util.Settings;
import com.olympia.myapp.util.WaitingReminder;
import com.olympia.myapp.xml.MyXMLParser;
import com.olympia.myapp.xml.QuestionXMLHandler;

public class VDActivity extends BaseActivity {
	TextView txtName;
	TextView txtNum;
	TextView txtContentQS;
	TextView txtAnserQS;
	TextView txtTime;
	TextView txtScore;
	Button btnA;
	Button btnB;
	Button btnC;
	Button btnD;

	// goi cau hoi
	RelativeLayout layout_pk;
	Button btn40;
	Button btn60;
	Button btn80;

	AnimationControl animaControl;
	Reminder remind;
	WaitingReminder waitingRemind;

	Dialog_Confirm dgConfirm;
	//
	List<QuestionVD> arrVDQS = null;
	List<QuestionVD> arrVDQSSelect = null;
	QuestionVD currQS = null;
	//
	int timeBegin = 39 * 1000;
	int timeWaiting = 1200;
	int timeMax = 30;
	int timeQuestion = 30;
	//
	int numQS = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.vdactivity);
		intent = getIntent();

		numQS = 0;
		animaControl = new AnimationControl();

		// khởi tạo control
		txtName = (TextView) findViewById(R.id.vd_layout_caption_name);
		txtName.setText(Constants.myAccount.name);
		txtNum = (TextView) findViewById(R.id.vd_layout_caption_totalNum);

		txtScore = (TextView) findViewById(R.id.vd_layout_right_score);
		setScore();
		txtTime = (TextView) findViewById(R.id.vd_layout_right_time);

		txtContentQS = (TextView) findViewById(R.id.vd_layout_question_content);
		txtAnserQS = (TextView) findViewById(R.id.vd_layout_question_answer);

		btnA = (Button) findViewById(R.id.vd_layout_bottom_btnA);
		btnA.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				clearFocus();
				btnA.setFocusableInTouchMode(true);
				return false;
			}
		});
		btnB = (Button) findViewById(R.id.vd_layout_bottom_btnB);
		btnB.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				clearFocus();
				btnB.setFocusableInTouchMode(true);
				return false;
			}
		});
		btnC = (Button) findViewById(R.id.vd_layout_bottom_btnC);
		btnC.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				clearFocus();
				btnC.setFocusableInTouchMode(true);
				return false;
			}
		});
		btnD = (Button) findViewById(R.id.vd_layout_bottom_btnD);
		btnD.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				clearFocus();
				btnD.setFocusableInTouchMode(true);
				return false;
			}
		});
		// gói
		layout_pk = (RelativeLayout) findViewById(R.id.vd_layout_package);
		btn40 = (Button) findViewById(R.id.vd_layout_pk_btn40);
		btn40.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				selectPkage(0);
			}
		});
		btn60 = (Button) findViewById(R.id.vd_layout_pk_btn60);
		btn60.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				selectPkage(1);
			}
		});
		btn80 = (Button) findViewById(R.id.vd_layout_pk_btn80);
		btn80.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				selectPkage(2);
			}
		});
		clearFocus();
		// lấy câu hỏi
		arrVDQS = QuestionXMLHandler.qsVD;

		// khởi tạo remind dể cập nhật thời gian
		remind = new Reminder(new ControlListener() {
			public void runTask() {
				Constants.myService.playClick();
				// cập nhật thời gian
				timeQuestion--;
				setTime(timeQuestion);
			}

			public void stopTask() {
				// reset lại thời gian
				timeQuestion = 30;
				// kiểm tra câu trả lời
				if (checkAnswer()) {
					// phat am thanh dug
					if (!isFinishing()) {
						int ran = (new Random()).nextInt(100) % 2;
						if (ran == 0)
							Constants.myService.playCorrect1();
						else
							Constants.myService.playCorrect2();
					}

					// cập nhật điểm
					Constants.SCORE += Integer.parseInt(currQS.score);
					// hien thị diem
					setScore();
				} else {
					// phat am thanh sai
					if (!isFinishing())
						Constants.myService.playUnCorrect2();
				}

				// reset lại nội dung
				clearFocus();
				showLayoutQS(false);
				// stop 5s rồi load câu mới
				waitingRemind.start(timeWaiting);
			}
		}, timeQuestion);
		// hiển thị dialog bắt đầu
		showDialogBegin();
		Constants.myService.playVD();
		// chạy control chờ trong thời gian phát âm thanh
		WaitingReminder beginRemind = new WaitingReminder(
				new ControlListener() {
					public void runTask() {
						// dimis dialog
						dgConfirm.dismiss();
						// tat am thanh

						// hiển thị gói câu hỏi để chọn
						layout_pk.setVisibility(View.VISIBLE);
						animaControl.RunAnimations(VDActivity.this, layout_pk,
								R.anim.anim_show_down);
						// không cho focus vào layout phia duoi
						((RelativeLayout) findViewById(R.id.vd_layout))
								.setVisibility(View.GONE);
					}
				});
		beginRemind.start(timeBegin);

		// khởi tạo control chờ để load câu hỏi
		waitingRemind = new WaitingReminder(new ControlListener() {
			public void runTask() {
				// tat am thanh

				// hiển thị gói câu hỏi để chọn
				loadQuestion();
			}
		});
		showLayoutQS(false);
	}

	private void setScore() {
		if (txtScore != null)
			txtScore.setText(String.valueOf(Constants.SCORE));
	}

	private void setTime(int time) {
		if (txtTime != null)
			txtTime.setText(String.valueOf(time));
	}

	/**
	 * ẩn hiện nội dung và nút bấm
	 */
	private void showLayoutQS(boolean isShow) {
		if (isShow) {
			((RelativeLayout) findViewById(R.id.vd_layout_bottom))
					.setVisibility(View.VISIBLE);
		} else {
			txtContentQS.setText("");
			txtAnserQS.setText("");
			((RelativeLayout) findViewById(R.id.vd_layout_bottom))
					.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * hiển thị dialog chờ để phát âm thanh trước khi bắt đầu phần chơi
	 * 
	 */
	private void showDialogBegin() {
		dgConfirm = new Dialog_Confirm(this, getString(R.string.note_title),
				"PHẦN THI VỀ ĐÍCH", false, false, new ProcessDialogConfirm() {
					public void click_Ok() {
					}

					public void click_Cancel() {
					}
				});
		dgConfirm.setCancelable(false);
		dgConfirm.show();
	}

	/**
	 * hiển thị dialog chờ để phát âm thanh trước khi bắt đầu phần chơi
	 * 
	 */
	private void showDialogConfirm() {
		if (!isFinishing()) {
			String str = String.format(
					getResources().getString(R.string.start_content_score),
					"VỀ ĐÍCH", Constants.SCORE);
			Dialog_Confirm dgConfirm = new Dialog_Confirm(this,
					getString(R.string.note_title), str, false, true,
					new ProcessDialogConfirm() {
						public void click_Ok() {
						}

						public void click_Cancel() {
							acceptScore();
						}
					});
			dgConfirm.setTextOnButton("", "Tiếp tục");
			dgConfirm.setCancelable(false);
			dgConfirm.show();
		}
	}

	/**
	 * trạng thái active
	 * 
	 * @param index
	 */
	private void clearFocus() {
		btnA.setFocusableInTouchMode(false);
		btnB.setFocusableInTouchMode(false);
		btnC.setFocusableInTouchMode(false);
		btnD.setFocusableInTouchMode(false);
		txtScore.setFocusable(true);
		txtScore.setFocusableInTouchMode(true);
		txtScore.requestFocus();
	}

	/**
	 * kiem tra chon button nao
	 * 
	 * @return
	 */
	private int checkBtnFocus() {
		int idFocus = 0;
		if (btnA.isFocusableInTouchMode())
			idFocus = 1;
		else if (btnB.isFocusableInTouchMode())
			idFocus = 2;
		else if (btnC.isFocusableInTouchMode())
			idFocus = 3;
		else if (btnD.isFocusableInTouchMode())
			idFocus = 4;
		return idFocus;
	}

	/**
	 * chọn gói câu hỏi
	 * 
	 * @param type
	 */
	private void selectPkage(int type) {
		int count = 4;
		Random ran = new Random();
		arrVDQSSelect = new ArrayList<QuestionVD>();
		switch (type) {
		case 0:// goi 40 gồm 4 câu 10đ
			for (int i = 0; i < count; i++) {
				arrVDQSSelect.add(arrVDQS.get(i));
			}
			break;
		case 1:// goi 60 gồm 2 câu 10đ, 2 câu 20đ
			int n = ran.nextInt(100) % 4;
			arrVDQSSelect.add(arrVDQS.get(n));
			if (n == 3)
				n--;
			else
				n++;
			arrVDQSSelect.add(arrVDQS.get(n));
			// 2 câu 20đ
			arrVDQSSelect.add(arrVDQS.get(4));
			arrVDQSSelect.add(arrVDQS.get(5));
			break;
		case 2:// goi 80 gồm 1 câu 10đ, 2 câu 20đ, 1 câu 30đ
			int m = ran.nextInt(100) % 4;
			arrVDQSSelect.add(arrVDQS.get(m));
			// 2 câu 20đ
			arrVDQSSelect.add(arrVDQS.get(4));
			arrVDQSSelect.add(arrVDQS.get(5));
			// 1 câu 30đ
			// 2 câu 20đ
			arrVDQSSelect.add(arrVDQS.get(6));
			break;

		default:
			for (int i = 0; i < count; i++) {
				arrVDQSSelect.add(arrVDQS.get(i));
			}
			break;
		}

		arrVDQS.clear();
		arrVDQS = null;
		// đóng layout này
		layout_pk.setVisibility(View.GONE);
		// cho focus vào layout phia duoi
		((RelativeLayout) findViewById(R.id.vd_layout))
				.setVisibility(View.VISIBLE);

		// bắt đầu hiển thị câu hỏi
		waitingRemind.start(1);
	}

	/**
	 * load câu hỏi
	 * 
	 */
	private void loadQuestion() {
		if (numQS < arrVDQSSelect.size()) {
			currQS = arrVDQSSelect.get(numQS);

			if (currQS != null) {
				showLayoutQS(true);
				txtContentQS.setText(currQS.content);
				txtAnserQS.setText(currQS.answerContent);

				animaControl.RunAnimations(this, txtContentQS, R.anim.tranlate);
				animaControl.RunAnimations(this, txtAnserQS, R.anim.tranlate);
				animaControl.RunAnimations(this, btnA, R.anim.alpha);
				animaControl.RunAnimations(this, btnB, R.anim.alpha);
				animaControl.RunAnimations(this, btnC, R.anim.alpha);
				animaControl.RunAnimations(this, btnD, R.anim.alpha);

				timeQuestion = Integer.parseInt(currQS.score);
				setTime(timeQuestion);

				// set tiêu đề
				txtNum.setText("Câu hỏi " + currQS.score + " điểm");
			}
			numQS++;
			// bat dau tinh thoi gian
			remind.resetTime(timeQuestion);
			remind.start(1);
			// clear select
			clearFocus();
		} else {
			// hien thị dialog để truyền điểm lên server
			showDialogConfirm();
		}
	}

	/**
	 * kiểm tra câu trả lời
	 * 
	 * @return
	 */
	private boolean checkAnswer() {
		boolean rs = false;
		String strAns = "";
		switch (checkBtnFocus()) {
		case 1:
			strAns = "A";
			break;
		case 2:
			strAns = "B";
			break;
		case 3:
			strAns = "C";
			break;
		case 4:
			strAns = "D";
			break;

		default:
			break;
		}

		if (currQS.answer.toUpperCase().compareTo(strAns) == 0) {
			rs = true;
		}

		return rs;
	}

	/**
	 * =================== gui yeu cau xac nhan diem len server
	 * ===================
	 */
	private void acceptScore() {
		String urlScore = urlUtil.acceptScore(Constants.myAccount.mail,
				String.valueOf(Constants.SCORE));
		requestServer(urlScore, 0);
	}

	String urlLogin;

	public void requestServer(String url, int id) {
		if (!isRequest) {
			Handler handler = new Handler() {
				@Override
				public void handleMessage(Message message) {
					switch (message.what) {
					case HttpConnection.DID_START: {
						break;
					}
					case HttpConnection.DID_SUCCEED: {
						// String result = message.obj.toString();
						// tiến hành login lại
						String[] str = Settings.getpPlayer(VDActivity.this);
						if (message.arg1 == 0) {
							urlLogin = urlUtil.login(Constants.VERSION, str[0],
									str[1]);
							requestServer(urlLogin, 1);
						} else {
							try {
								// parser du lieu
								URL sourceUrl = new URL(urlLogin);
								List<String> content = MyXMLParser
										.parseLoginData(new InputSource(
												sourceUrl.openStream()));
								if (content != null && content.size() > 0) {
									if (content.get(0).toString().toUpperCase()
											.equals("OK")) {
										Constants.myAccount = new Player(1000,
												content.get(1), str[0],
												content.get(2), content.get(3),
												content.get(4), content.get(5),
												content.get(6));
									}
								}
							} catch (Exception e) {
							}

							intent = new Intent(VDActivity.this,
									PlayerListActivity.class);
							intent.putExtra("pass", str[1]);
							startActivity(intent);
							overridePendingTransition(R.anim.fase_in,
									R.anim.fade_out);
							finish();
						}
						break;
					}
					case HttpConnection.DID_ERROR: {
						msgUtil.showToast(VDActivity.this,
								getString(R.string.error_connect));
						break;
					}
					}
				}
			};

			new HttpConnection(handler).get(url, id);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		Constants.myService.clearAll();
		super.onBackPressed();
	}
}
